import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_channel.dart';
import 'package:flutter_boost/boost_flutter_binding.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_boost/flutter_boost_app.dart';
import 'package:flutter_boost/page_visibility.dart';
import 'package:flutter_module/common/route/dialog_routes.dart';
import 'package:flutter_module/routers.dart';
import 'common/utils/extensions.dart';

// main dart 改造成多入口的模式，以便我们app能够多个模块来启动，但至少保留一个主入口

//这是我们的主入口
void main() {
  //在runApp之前确保BoostFlutterBinding初始化
  CustomFlutterBinding();
  runApp(MyApp());
}

final GlobalKey AppGlobalKey = GlobalKey();

class MyApp extends StatefulWidget {
  final String? initialRoute;
  MyApp({Key? key, this.initialRoute}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();

// @override
// Widget build(BuildContext context) {
//   return MaterialApp(
//       title: 'Flutter Title',
//       routes: _getRouters(),
//       home: Scaffold(
//         key: AppGlobalKey,
//         body: page,
//       ));
// }
// _getRouters() {
//   HashMap<String , WidgetBuilder> routermap = new HashMap();
//   routermap.addAll(playgroundRouterMap);
//   return routermap;
// }
}

class _MyAppState extends State<MyApp> with GlobalPageVisibilityObserver {
  var _numberOfPagesInRoute = 0;

  ///路由表
  static Map<String, FlutterBoostRouteFactory> routerMap = Map();

  @override
  void initState() {
    routerMap = (cooperationRouterTable + dialogRouterTable);
    // routerMap.addAll(cooperationRouterTable);
    super.initState();
    PageVisibilityBinding.instance.addGlobalObserver(this);
  }

  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory? func = routerMap[settings.name];
    if (func == null) {
      return null;
    }
    return func(settings, uniqueId);
  }

  @override
  Widget build(BuildContext context) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: (home) => MaterialApp(
        home: Scaffold(
          key: AppGlobalKey,
          body: home,
        ),
      ),
      initialRoute: widget.initialRoute,
    );
  }

  @override
  void dispose() {
    super.dispose();
    PageVisibilityBinding.instance.removeGlobalObserver(this);
  }

  @override
  void onPagePush(Route<dynamic> route) {
    super.onPagePush(route);
    _numberOfPagesInRoute++;
    print('当前路由中的页面数量：$_numberOfPagesInRoute');
    _updateNumberOfPagesInRoute();
  }

  @override
  void onPagePop(Route<dynamic> route) {
    super.onPagePop(route);
    _numberOfPagesInRoute--;
    print('当前路由中的页面数量：$_numberOfPagesInRoute');
    _updateNumberOfPagesInRoute();
  }

  void _updateNumberOfPagesInRoute() {
    BoostChannel.instance.sendEventToNative(
        'numberOfPagesInRoute', {'numbers': _numberOfPagesInRoute});
  }
}

class CustomFlutterBinding extends WidgetsFlutterBinding
    with BoostFlutterBinding {}
